/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.utils;

public class CustStringTokenizer {
	public CustStringTokenizer(String input, Character delimiter, Character quoteCharacter)
	{
		_input = input;
		_delimiter = delimiter;
		_quoteCharacter = quoteCharacter;
	}
	
	private final String _input;
	
	private final Character _delimiter;
	
	private final Character _quoteCharacter;
	
	private int _scanHead = 0;
	
	public String nextToken()
	{
		String token = null;
		if(_scanHead >= _input.length())
			return null;
		
		// Scan input from current scan head position until delimiter or quote character found
		int scanHead = _scanHead;
		int quotesFound = 0;
		while(scanHead < _input.length())
		{
			Character currentChar = _input.charAt(scanHead);
			
			if(currentChar.equals(_delimiter) && (quotesFound % 2 == 0))
			{
				if( _scanHead == scanHead - 1 )
					token = "";
				else
					token = _input.substring(_scanHead, scanHead);
				_scanHead = scanHead + 1;
				if(quotesFound > 0)
					token = token.substring(1, token.length() - 1).replace(",", "");
				return token;
			}
			
			if(currentChar.equals(_quoteCharacter))
				quotesFound++;
			
			scanHead++;
		}
		
		token = _input.substring(_scanHead);
		_scanHead = _input.length();
		return token;
	}
}
